﻿using System.Collections.Generic;
using DataScripter.Database;
using DataScripter.Scripting.ScriptDefinitions;

namespace DataScripter.Scripting.Filters
{
    public class ForeignKeyFilter : IForeignKeyFilter
    {
        private IScriptDefinition ScriptDefinition { get; set; }
        public IForeignKey ForeignKey { get; private set; }
        public ITableScriptRequest TableScriptRequest { get; set; }

        public ForeignKeyFilter(IForeignKey foreignKey, ITableScriptRequest tableScriptRequest, IScriptDefinition engine)
        {
            ScriptDefinition = engine;
            ForeignKey = foreignKey;
            TableScriptRequest = tableScriptRequest;
        }

        public string ProduceFilter()
        {
            IForeignKey foreignKey = ForeignKey;
            IDictionary<string, ITableScriptRequest> scriptRequests = ScriptDefinition.ScriptRequests;
            string referencedTableName = foreignKey.ReferencedTableName;
            if (referencedTableName == TableScriptRequest.TableName)
            {
                referencedTableName = foreignKey.TableName;
            }
            ITableScriptRequest foreignTableScriptRequest = scriptRequests.ContainsKey(referencedTableName) ? scriptRequests[referencedTableName] : null;
            string whereClause = foreignTableScriptRequest == null ? string.Empty : foreignTableScriptRequest.ProduceWhereClause();
            return string.Format("{0} IN (SELECT {1} FROM {2}{3})", foreignKey.ColumnName, foreignKey.ReferencedColumnName, referencedTableName, whereClause);
        }

        public string ProduceWhereClause()
        {
            string netWhereClause = ProduceFilter();
            return string.IsNullOrEmpty(netWhereClause) ? string.Empty : " WHERE " + netWhereClause;
        }
    }
}